package 接口.基础;

import java.util.Arrays;
import java.util.Comparator;

//自定义类型想要比较大小需要使用这个接口
//缺点：拓展性太差
class Student implements Comparable<Student> {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
//        if (this.age > o.age) {
//            return 1;
//        } else if (this.age < o.age) {
//            return -1;
//        } else {
//            return 0;
//        }
    }

    //冒泡排序
    public static void fun1(Comparable[] comparables){
        for (int i = 0; i < comparables.length-1; i++) {
            for (int j = 0; j < comparables.length-i-1; j++) {
                if(comparables[j].compareTo(comparables[j+1])>0){
                    Comparable stem =  comparables[j];
                    comparables[j] =comparables[j+1];
                    comparables[j+1] = stem;
                }
            }
        }
    }
}

//2.比较器,需要的比较,专门写出来比较灵活
class AgeCompare implements Comparator<Student> {

    @Override
    public  int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }

    public static void fun1(Student[] students,Comparator<Student> comparator) {
        for (int i = 0; i < students.length - 1; i++) {
            for (int j = 0; j < students.length - i - 1; j++) {
                if(comparator.compare(students[j],students[j+1])>0){
                    Student stem =  students[j];
                    students[j] =students[j+1];
                    students[j+1] = stem;
                }
            }
        }
    }
}
class NameCompare implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}
public class Comparable_1 {
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("张三", 12);
        students[1] = new Student("李四", 28);
        students[2] = new Student("王五", 19);

        Arrays.sort(students);
        //使用自己定义冒泡排序
//        Student.fun1(students);
        //使用比较器
//        AgeCompare ageCompare = new AgeCompare();
//        ageCompare.fun1(students,ageCompare);


        System.out.println(Arrays.toString(students));

    }
}
